/*
 * User: rant
 * Date: 14/02/2007
 *
 *
 */
package laMalinche.rete.nodes.tailing;

import laMalinche.testingPlayGround.testModel.ChangeListener;
import laMalinche.testingPlayGround.testModel.EntityChangeEvent;
import laMalinche.testingPlayGround.testModel.VOEntity;
import laMalinche.rete.nodes.ConditionNode;
import org.jetbrains.annotations.NotNull;

import java.util.*;

/**
 *
 */
public class BasicWorkingMemory extends WorkingMemoryListenable implements WorkingMemory, ChangeListener {


	private final List<VOEntity> relevantFields;
	//	private boolean propertyChangeNotSupportedFlag = false;
	private ConditionNode conditionNode;

	public ConditionNode getConditionNode() {
		return conditionNode;
	}

	public BasicWorkingMemory() {
		relevantFields = new ArrayList<VOEntity>(10);
	}

	protected boolean isChangable() {
		return getConditionNode().getCondition().isDisjunction();
	}

	protected void addRelevantField(VOEntity field) {
		field.addChangeListener(this);
		relevantFields.add(field);
	}

	public List<VOEntity> getRelevantFields() {
		return relevantFields;
	}

	protected void setRelevantFields(List<VOEntity> relevantFields) {
		for (VOEntity field : relevantFields) {
			addRelevantField(field);
		}
	}


	public void adviseCahnge() {
		fireWorkingMemoryChangeEvent(null);
	}

	private void removeFieldListeners() {
		for (VOEntity field : relevantFields) {
			field.removeChangeListener(this);
		}
	}

	public void setConditionNode(ConditionNode conditionNode) {
		this.conditionNode = conditionNode;
		addWorkingMemoryListener(conditionNode);
	}


	public void actCompleted(List<VOEntity> elements) {
		removeFieldListeners();
		setRelevantFields(elements);
	}

	public void detach() {
		removeFieldListeners();
	}



	private void fireWorkingMemoryChangeEvent(Boolean toValue) {
		WorkingMemoryEvent event = new WorkingMemoryEvent();
		event.setConditionMet(toValue);
		for (WorkingMemoryChangeListener listener : getWorkingMemoryListeners()) {
			listener.workingMemoryChange(event);
		}
	}

	public void propertyTouched(VOEntity entity) {
	}



	public void entityChange(@NotNull EntityChangeEvent event) {
			fireWorkingMemoryChangeEvent(null);
	}
}